package office.stock.security.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import office.stock.model.User;
import office.stock.security.SessionAttributes;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@WebFilter("*.xhtml")
public class AuthenticationFilter implements Filter {

    private static final Log log = LogFactory.getLog(AuthenticationFilter.class);

    @Override
    public void destroy() {

    }
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) servletRequest;
	HttpServletResponse response = (HttpServletResponse) servletResponse;

	String requestURI = request.getRequestURI();

	String contextPath = request.getContextPath();

	String localPath = requestURI.replaceFirst(contextPath, "");

	if (localPath.contains("/secured/")) {
	    User user = (User) request.getSession(true).getAttribute(SessionAttributes.USER.name());
	    if (user == null) {
		request.getSession().setAttribute(SessionAttributes.TARGET_PAGE.name(), localPath);
		response.sendRedirect(response.encodeRedirectURL(contextPath + "/public/login.xhtml"));
	    }
	}

	filterChain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
	log.info("Custom authentication filter was created");
    }

}
